package com.spring.ioc;

import com.spring.bean.*;
import com.spring.origin.UserDao;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;

import java.util.List;

public class TestSpring {

    private final Log log = LogFactory.getLog(getClass());

    ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");

    /**
     * 通过xml配置获取创建对象
     */
    @Test
    public void createObj(){
        // 1、加载spring配置文件
        // ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
        //需要xml全路径
        //ApplicationContext context = new FileSystemXmlApplicationContext("bean1.xml");
        // 2、获取配置创建对象(userDao:xml中的id属性名)
        UserDao dao = context.getBean("userDao", UserDao.class);
        dao.create();
    }

    /**
     * 通过set方法注入属性
     */
    @Test
    public void getProperty(){
        User user = context.getBean("user", User.class);
        System.out.println("获取xml中property获取的属性：" + user.getId());
    }

    /**
     * 通过有参构造方法注入属性
     */
    @Test
    public void getPropertyByXml(){
        Book book = context.getBean("book", Book.class);
        System.out.println("获取xml中constructor-arg注入属性：" + book.author + " " + book.bookName);
    }

    @Test
    public void innerBean(){
        ApplicationContext context = new ClassPathXmlApplicationContext("bean2.xml");
        Emp emp = context.getBean("emp",Emp.class);
        System.out.println("emp:"+emp.getName());
        Dept dept = context.getBean("dept", Dept.class);
        System.out.println("dept:"+dept.getName());
        List<Emp> list = dept.getEmpList();
        for (Emp item:list) {
            System.out.println("编号："+item.getId()+"  姓名："+item.getName());
        }
        log.info(dept);
    }

    /**
     * 注入集合属性
     */
    @Test
    public void DISetProperty(){
        ApplicationContext context = new ClassPathXmlApplicationContext("bean2.xml");
        Student student = context.getBean("student",Student.class);
        System.out.println(student.toString());
    }
}
